﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RestSharp;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Net.Security;
using System.Web;
using Newtonsoft.Json;
using System.IO;

namespace DosciWordPlugin.Common
{
    public static class HttpUtil
    {
        public static event Action TokenExpiredEvent;

        public const string CODE_OK = "0";
        public const string CODE_TOKEN_ERROR = "400001";

        public class AjaxResult<T>
        {
            public string Code { get; set; }
            public string Message { get; set; }
            public T Body { get; set; }
        }

        private static RestClient _client;

        public static void Init() 
        {
            try
            {
                _client = new RestClient(Constant.HOST);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }

        public static T Post<T>(string apiUri, Dictionary<string, string> parameters)
        {
            try
            {
                var request = new RestRequest(apiUri, Method.POST);
                
                if (apiUri != Constant.API_登陆 && apiUri != Constant.API_样式列表)
                    request.AddParameter("token", CacheManager.UserInfo.Token);

                if (parameters != null)
                {
                    foreach (var item in parameters)
                        request.AddParameter(item.Key, item.Value);
                        //request.AddParameter(item.Key, System.Web.HttpUtility.UrlEncode(item.Value));
                }

                var response = _client.Execute<AjaxResult<T>>(request);

                if (response.ErrorMessage != null)
                    throw new HttpException(response.ErrorMessage);
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    throw new HttpException(response.StatusDescription);

                if (response.Data.Code == CODE_TOKEN_ERROR)
                {
                    CacheManager.SetUserInfo(null);
                    if (TokenExpiredEvent != null) TokenExpiredEvent();
                    throw new HttpException("Token 已过期，请重新登录！");
                }

                if (response.Data.Code != CODE_OK)
                    throw new HttpException(response.Data.Message);

                if (apiUri == Constant.API_退出)
                    CacheManager.SetUserInfo(null);

                return response.Data.Body;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void DownloadFile(string apiUri, Dictionary<string, string> parameters, string savePath, bool isPOST = false)
        {
            try
            {
                if (apiUri.IndexOf(Constant.HOST) >= 0)
                    apiUri = apiUri.Replace(Constant.HOST, "");

                var request = new RestRequest(apiUri, isPOST ? Method.POST : Method.GET);

                if (apiUri != Constant.API_登陆 && apiUri != Constant.API_样式列表)
                    request.AddParameter("token", CacheManager.UserInfo.Token);

                if (parameters != null)
                {
                    foreach (var item in parameters)
                        request.AddParameter(item.Key, item.Value);
                    //request.AddParameter(item.Key, System.Web.HttpUtility.UrlEncode(item.Value));
                }

                byte[] dataBytes = _client.DownloadData(request);
                File.WriteAllBytes(savePath, dataBytes);
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static void UploadFile(string fileName, string filePath)
        {
            try
            {
                var request = new RestRequest(Constant.API_上传文档, Method.POST);
                request.AddParameter("token", CacheManager.UserInfo.Token);
                request.AddFile(fileName, filePath);

                _client.Execute(request);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
